Wow so easy
This commit is contained in:
27
api/api.go
Normal file
27
api/api.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"encoding/json"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Age uint8 `json:"age"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := User{"johnnyBoy", "John Doe", 20}
|
||||||
|
jsonBytes, err := json.Marshal(user)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Interal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _err := w.Write(jsonBytes)
|
||||||
|
if _err != nil {
|
||||||
|
http.Error(w, "Interal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
18
main.go
Normal file
18
main.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.cems.dev/cdricms/go-api/api"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
http.HandleFunc("/user", api.GetUserHandler)
|
||||||
|
port := 8080
|
||||||
|
fmt.Printf("Server running on : %d\n", port)
|
||||||
|
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error: ", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user