Skip to content

Instantly share code, notes, and snippets.

@rakaadinugroho
Created July 17, 2018 01:40
Show Gist options
  • Save rakaadinugroho/a45b5d4d659d0641e290f667683d1543 to your computer and use it in GitHub Desktop.
Save rakaadinugroho/a45b5d4d659d0641e290f667683d1543 to your computer and use it in GitHub Desktop.
Basic Http : Tutorial Golang Bahasa Indonesia
1. Menambahkan HTTP Package
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprint(writer, "test browser")
})
http.ListenAndServe(":8080", nil)
2. Create Enpoint (untuk ujicoba)
http.HandleFunc("/test", otherFunc)
3. Http Verb
func otherFunc(writer http.ResponseWriter, request *http.Request) {
switch request.Method {
case "POST":
}
if == "POST" {
} else {
http.Error(writer, "Invalid request method, you use " + queryValues.Get("username"), http.StatusMethodNotAllowed)
}
}
4. Membaca Arguments / Params (Path, Query, Body)
#Field
Formrequest.FormValue("field")
#Queries
queryValues := request.URL.Query()
queryValues.Get("field")
#Path
request.URL.Path[len("/endpoint/"):]
#Body
type LoginBody struct {
Username string `json:"username"`
Password string `json:"password"`
}
b, err := ioutil.ReadAll(request.Body)
defer request.Body.Close()
var reqs LoginBody
err = json.Unmarshal(b, &reqs)
// reqs sudah bisa digunakan
5. Membuat Response ()
http.Error(writer, "invalide method", http.StatusMethodNotAllowed)
//Json Response
responseWithMap := map[string]interface{}{
"data" : "what?",
"status" : http.StatusOK,
}
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
json.NewEncoder(writer).Encode(responseWithMap)
return
Terimakasih jangan lupa Vidio Tutorial Terbaru ada di:
https://www.youtube.com/channel/UCbffo0dSFr91k7W7Sa8YQVg
Kembangkan karir kalian di dunia IT Sekarang!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment