Last active
April 26, 2017 14:07
-
-
Save deankarn/1053ccba890521c8607ea8b29d5d626d to your computer and use it in GitHub Desktop.
std net/http is enough PI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"strings" | |
) | |
func main() { | |
mux := http.NewServeMux() | |
mux.HandleFunc("/user/", userHandler) // to handle /user/:id | |
http.ListenAndServe(":8080", mux) | |
} | |
func userHandler(w http.ResponseWriter, r *http.Request) { | |
// | |
// we need to handle the following: | |
// /user/:id | |
// | |
// I'm not converting :id to integer or GUID... | |
// | |
param := r.URL.Path[6:] | |
idx := strings.Index(param, "/") | |
if idx == -1 { | |
// url /user/:id we're all set | |
fmt.Fprintf(w, "/user/:id id=%s", param) | |
return | |
} | |
static := param[idx+1:] | |
// found slash but no more to the URL | |
if len(static) == 0 { | |
http.Redirect(w, r, r.URL.Path[:len(r.URL.Path)-1], http.StatusMovedPermanently) | |
return | |
} | |
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment