Created
September 27, 2020 15:53
-
-
Save jufianto/7a335d89a5532fcf77f0f742b4ead5e1 to your computer and use it in GitHub Desktop.
Golag Example Test Cide
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 ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"testgolang/model" | |
) | |
func main() { | |
helloHandler := func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("Testing Handler") | |
w.WriteHeader(200) | |
w.Header().Set("Content-Type", "application/json") | |
text := "Selamat Datang" | |
w.Write([]byte(text)) | |
} | |
restHandler := func(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Set-Cookie") | |
w.WriteHeader(200) | |
if r.Method != http.MethodGet { | |
http.NotFound(w, r) | |
return | |
} | |
var blogData model.Blog | |
body, err := ioutil.ReadAll(r.Body) | |
err = json.Unmarshal(body, &blogData) | |
if err != nil { | |
log.Println(err) | |
} | |
// proses logic | |
var blogResponse model.BlogResponse | |
if blogData.ID > 5 { | |
blogResponse.Kategori = "BERITA" | |
} else { | |
blogResponse.Kategori = "NONE" | |
} | |
blogResponse.ID = blogData.ID | |
blogResponse.Text = blogData.Text | |
b, _ := json.Marshal(blogResponse) | |
w.WriteHeader(200) | |
w.Write([]byte(b)) | |
} | |
http.HandleFunc("/test", helloHandler) | |
http.HandleFunc("/blog", restHandler) | |
port := 1234 | |
log.Println("Starting in port", port) | |
http.ListenAndServe(":1234", nil) | |
} |
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 model | |
// IN FOLDER model | |
type Blog struct { | |
ID int `json:"id_blog"` | |
Text string `json:"text"` | |
} | |
type BlogResponse struct { | |
ID int `json:"id"` | |
Text string `json:"text"` | |
Kategori string `json:"kategori"` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment