Created
September 5, 2015 19:43
-
-
Save jhoonb/d0f073e9b4fb19840da3 to your computer and use it in GitHub Desktop.
example web golang
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
| // github.com/jhoonb | |
| package main | |
| import ( | |
| "log" | |
| "net/http" | |
| ) | |
| // view | |
| // APiFunc | |
| func ApiFunc(w http.ResponseWriter, r *http.Request) { | |
| w.Write([]byte("rota api")) | |
| } | |
| // APiTest | |
| func ApiTest(w http.ResponseWriter, r *http.Request) { | |
| w.Write([]byte("rota api teste")) | |
| } | |
| // WebIndex | |
| func WebIndex(w http.ResponseWriter, req *http.Request) { | |
| // nome do arquivo no diretorio | |
| render(w, "index.html") | |
| } | |
| // WebTest | |
| func WebTest(w http.ResponseWriter, req *http.Request) { | |
| // nome do arquivo no diretorio | |
| render(w, "test.html") | |
| } | |
| // render renderiza o template passado por parametro em tmpl | |
| // para o responser w | |
| func render(w http.ResponseWriter, tmpl string) { | |
| tmpl = fmt.Sprintf("templates/%s", tmpl) | |
| tf, err := template.ParseFiles(tmpl) | |
| if err != nil { | |
| log.Println("template parsing error: ", err) | |
| } | |
| err = tf.Execute(w, "") | |
| if err != nil { | |
| log.Println("template executing error: ", err) | |
| } | |
| } | |
| // main | |
| func main() { | |
| // static files js/css | |
| // estrutura de diretorio /static/js/ - /static/css/ | |
| http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) { | |
| http.ServeFile(w, r, r.URL.Path[1:]) | |
| }) | |
| // rotas web renderiza os templates | |
| http.HandleFunc("/", WebIndex) | |
| http.HandleFunc("/test", WebTest) | |
| // api | |
| http.HandleFunc("/api", ApiFunc) | |
| http.HandleFunc("/api/test", ApiTest) | |
| log.Fatal(http.ListenAndServe(":5000", nil)) // run | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment