Skip to content

Instantly share code, notes, and snippets.

@birowo
Last active November 12, 2018 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save birowo/22f8007e932c1b5fbc11107741926848 to your computer and use it in GitHub Desktop.
Save birowo/22f8007e932c1b5fbc11107741926848 to your computer and use it in GitHub Desktop.
GOLANG. coba aplikasi yang menggunakan http router dibuat seperti(meski tidak secanggih) graphql . di sini saya buat untuk method GET request saja.
package main
import (
"encoding/json"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/julienschmidt/httprouter"
)
type Hitung struct {
Kali float64 `json:"kali,omitempty"`
Bagi float64 `json:"bagi,omitempty"`
Plus float64 `json:"plus,omitempty"`
Minus float64 `json:"minus,omitempty"`
}
type Lingkaran struct {
Keliling float64 `json:"keliling,omitempty"`
Luas float64 `json:"luas,omitempty"`
}
type Bola struct {
Luas float64 `json:"luas,omitempty"`
Isi float64 `json:"isi,omitempty"`
}
var hostPage = []byte(`
<html>
<head></head>
<body>
queries:<br>
<textarea id="qs_"></textarea><br>
<button onclick="getJSON('/?query='+qr.query(qs_.value), qr.result)">submit</button><br>
<br>
response:<br>
<textarea id="rs_"></textarea>
<script>
function getJSON(url, cb){
//alert(url)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
//alert(this.responseText)
if(this.getResponseHeader('Content-Type')=='application/json') cb(JSON.parse(this.responseText))
else alert('error: response must json')
}
}
xhr.open('GET', url);
xhr.send();
}
var qr = (function(rs_){
var keys
return {
query: function(qs){
qs = qs.replace(/^\s+|\s+$/g, '').replace(/\s+/g, '|')
keys = qs.split('|')
return qs
},
result: function(vals){
var json={}
for(var i=0; i<vals.length; i++){
json[keys[i].split('?')[0]]=vals[i]
}
rs_.value = JSON.stringify(json, null, '. ')
}
}
})(rs_)
</script>
</body>
</html>
`)
func main() {
r1 := httprouter.New()
r1.GET("/hitung/angka1/:angka1/angka2/:angka2", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
angka1, _ := strconv.ParseFloat(p.ByName("angka1"), 64)
angka2, _ := strconv.ParseFloat(p.ByName("angka2"), 64)
prop := strings.Split(r.URL.Query().Get("prop"), ",")
hitung := &Hitung{}
for _, field := range prop {
switch field {
case "plus":
hitung.Plus = angka1 + angka2
case "minus":
hitung.Minus = angka1 - angka2
case "kali":
hitung.Kali = angka1 * angka2
case "bagi":
hitung.Bagi = angka1 / angka2
}
}
//println("hitung")
json.NewEncoder(w).Encode(hitung)
})
r1.GET("/lingkaran/radius/:radius", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
radius, _ := strconv.ParseFloat(p.ByName("radius"), 64)
prop := strings.Split(r.URL.Query().Get("prop"), ",")
lingkaran := &Lingkaran{}
for _, field := range prop {
switch field {
case "keliling":
lingkaran.Keliling = 2 * math.Pi * radius
case "luas":
lingkaran.Luas = math.Pi * radius * radius
}
}
//println("lingkaran")
json.NewEncoder(w).Encode(lingkaran)
})
r1.GET("/bola/radius/:radius", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
radius, _ := strconv.ParseFloat(p.ByName("radius"), 64)
prop := strings.Split(r.URL.Query().Get("prop"), ",")
bola := &Bola{}
for _, field := range prop {
switch field {
case "luas":
bola.Luas = 4 * math.Pi * radius * radius
case "isi":
bola.Isi = (4 / 3) * math.Pi * radius * radius * radius
}
}
//println("bola")
json.NewEncoder(w).Encode(bola)
})
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
if len(query) == 0 {
w.Header().Set("Content-Type", "text/html")
w.Write(hostPage)
return
}
for k, v := range query {
switch k {
case "query":
urls := strings.Split(v[0], "|")
i, n := 0, len(urls)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("["))
for i < n {
r.URL, _ = url.Parse(urls[i])
//println(r.URL.Path)
i++
h, p, _ := r1.Lookup(r.Method, r.URL.Path)
if h != nil {
h(w, r, p)
if i < n {
w.Write([]byte(","))
}
}
}
w.Write([]byte("]"))
return
default:
http.Error(w, "resource not found", http.StatusNotFound)
}
}
}))
}

beberapa contoh query:

q1 q2 q3 q4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment