Hi, 

Am new in golang and am trying to write an API but my request header and 
body is always empty.
I need help on how to solve this Please.

Thanks in advance.

// Model
type NfInstance struct {
Id             bson.ObjectId         `json:"nfInstanceID" 
bson:"_id,omitempty"` //`json:"nfinstanceID" bson:"_id"`
ValidityPeriod int                   `json:"validityPeriod" 
bson:"alidityPeriod"`
NfInstanceID   string                `json:"nfinstanceId" 
bson:"nfinstanceId"`
HeartBeatTimer int                   `json:"heartBeatTimer" 
bson:"heartBeatTimer"`
SNssais        []SNssai              `json:"sNssais " bson:"sNssais"`
NsiList        []string              `json:"nsiList" bson:"nsiList"`
NfServices     []NfInstanceNfService `json:"nfServices" bson:"nfServices"`
}

type SNssai struct {
Sst int    `json:"sst" bson:"sst"`
Sd  string `json:"sd" bson:"sd"`
}

type NfInstanceNfService struct {
ServiceInstanceID string                        `json:"serviceInstanceId" 
bson:"serviceInstanceId"`
Versions          []NfInstanceNfServicesVersion `json:"versions" 
bson:"versions"`
}

type NfInstanceNfServicesVersion struct {
APIVersionInURI string    `json:"apiVersionInUri" bson:"apiVersionInUri"`
APIFullVersion  string    `json:"apiFullVersion" bson:"apiFullVersion"`
Expiry          time.Time `json:"expiry" bson:"expiry"`
}



// main

type NfInstancesCollection struct {
NfInstances []models.NfInstance `json:"nf-instances"`
}

type NfInstanceResource struct {
NfInstances models.NfInstance `json:"nf-Instances"`
}

type NfInstanceRepo struct {
coll *mgo.Collection
}

type NfSubsciptioneResource struct {
Subsciption models.Subscriptions `json:"subscriptions"`
}

type SubscriptionRepo struct {
coll *mgo.Collection
}

// ===========================================================
// Functions
//============================================================

func (r *NfInstanceRepo) All() (NfInstancesCollection, error) {
result := NfInstancesCollection{[]models.NfInstance{}}

err := r.coll.Find(nil).All(&result.NfInstances)
if err != nil {
return result, err
}

return result, nil
}

func (r *NfInstanceRepo) Find(id string) (NfInstanceResource, error) {
result := NfInstanceResource{}
err := r.coll.FindId(bson.ObjectIdHex(id)).One(&result.NfInstances)
if err != nil {
return result, err
}

return result, nil
}

func (r *NfInstanceRepo) Create(nfinstance *models.NfInstance) error {
id := bson.NewObjectId()
_, err := r.coll.UpsertId(id, nfinstance)
if err != nil {
return err
}

nfinstance.Id = id

return nil
}

func (r *NfInstanceRepo) Update(nfinstance *models.NfInstance) error {
err := r.coll.UpdateId(nfinstance.Id, nfinstance)
if err != nil {
return err
}

return nil
}

func (r *NfInstanceRepo) Delete(id string) error {
err := r.coll.RemoveId(bson.ObjectIdHex(id))
if err != nil {
return err
}

return nil
}

func (r *SubscriptionRepo) Createsub(nfsub *models.Subscriptions) error {
id := bson.NewObjectId()
_, err := r.coll.UpsertId(id, nfsub)
if err != nil {
return err
}

nfsub.Id = id

return nil
}

func (r *SubscriptionRepo) Deletesub(id string) error {
err := r.coll.RemoveId(bson.ObjectIdHex(id))
if err != nil {
return err
}

return nil
}

func (r *SubscriptionRepo) Updatesub(nfsub *models.Subscriptions) error {
err := r.coll.UpdateId(nfsub.Id, nfsub)
if err != nil {
return err
}

return nil
}

//===========================================================
//Api Context
type apiContext struct {
db *mgo.Database
}

//============================================================
//==================================================================================
// Handler Functions
//==================================================================================

//Not working
// ======================================================================
func (c *apiContext) GetNfInstanceUrls(w http.ResponseWriter, r 
*http.Request) {
repo := 
NfInstanceRepo{c.db.C("nfInstance[0].nfInstance.nfServices[0].versions[0].apiVersionInUri")}
nfinstancesurls, err := repo.All()
if err != nil {
panic(err)
}

//[0].nfInstances.nfServices[0].versions[0].apiVersionInUri)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(nfinstancesurls)
}

func (c *apiContext) SearchAllNfInstances(w http.ResponseWriter, r 
*http.Request) {
repo := NfInstanceRepo{c.db.C("nf-Instances")}
nfinstance, err := repo.All()
if err != nil {
panic(err)
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(nfinstance)
}

func (c *apiContext) GetNfInstancebyID(w http.ResponseWriter, r 
*http.Request) {
params := context.Get(r, "params").(httprouter.Params)

repo := NfInstanceRepo{c.db.C("nf-Instances")}
nfinstance, err := repo.Find(params.ByName("nfInstanceID"))
if err != nil {
panic(err)
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(nfinstance)
}

func (c *apiContext) RegisterNewNfInstance(w http.ResponseWriter, r 
*http.Request) {
ua := r.Header["header"]

body := context.Get(r, "body").(*NfInstanceResource)
fmt.Println(ua)
fmt.Println(body)
repo := NfInstanceRepo{c.db.C("nf-Instances")}
err := repo.Create(&body.NfInstances)
if err != nil {
panic(err)
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
json.NewEncoder(w).Encode(body)
}

func (c *apiContext) UpdateNfInstance(w http.ResponseWriter, r 
*http.Request) {
params := context.Get(r, "params").(httprouter.Params)
body := context.Get(r, "body").(*NfInstanceResource)
body.NfInstances.Id = bson.ObjectIdHex(params.ByName("nfInstanceID"))
repo := NfInstanceRepo{c.db.C("nf-Instances")}
err := repo.Update(&body.NfInstances)
if err != nil {
panic(err)
}

w.WriteHeader(204)
w.Write([]byte("\n"))
}

func (c *apiContext) DeregisterNfInstance(w http.ResponseWriter, r 
*http.Request) {
params := context.Get(r, "params").(httprouter.Params)
repo := NfInstanceRepo{c.db.C("nf-Instances")}
err := repo.Delete(params.ByName("nfInstanceID"))
if err != nil {
panic(err)
}

w.WriteHeader(204)
w.Write([]byte("\n"))
}

func (c *apiContext) CreateNewSubscription(w http.ResponseWriter, r 
*http.Request) {
body := context.Get(r, "body").(*NfSubsciptioneResource)
repo := SubscriptionRepo{c.db.C("subscriptions")}
err := repo.Createsub(&body.Subsciption)
if err != nil {
panic(err)
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
json.NewEncoder(w).Encode(body)
}

func (c *apiContext) deregisterSubscriptionbyID(w http.ResponseWriter, r 
*http.Request) {
params := context.Get(r, "params").(httprouter.Params)
repo := SubscriptionRepo{c.db.C("subscriptions")}
err := repo.Deletesub(params.ByName("nfInstanceID"))
if err != nil {
panic(err)
}

w.WriteHeader(204)
w.Write([]byte("\n"))
}

func (c *apiContext) updateAsubscriptionbyID(w http.ResponseWriter, r 
*http.Request) {
params := context.Get(r, "params").(httprouter.Params)
body := context.Get(r, "body").(*NfSubsciptioneResource)
body.Subsciption.Id = bson.ObjectIdHex(params.ByName("nfInstanceID"))
repo := SubscriptionRepo{c.db.C("subscriptions")}
err := repo.Updatesub(&body.Subsciption)
if err != nil {
panic(err)
}

w.WriteHeader(204)
w.Write([]byte("\n"))
}

//=============================================
// Router Struct
type router struct {
*httprouter.Router
}

//==============================================

// Methods wrappers
//=================================================
func (r *router) Get(path string, handler http.Handler) {
r.GET(path, wrapHandler(handler))
}

func (r *router) Patch(path string, handler http.Handler) {
r.PATCH(path, wrapHandler(handler))
}

func (r *router) Post(path string, handler http.Handler) {
r.POST(path, wrapHandler(handler))
}

func (r *router) Put(path string, handler http.Handler) {
r.PUT(path, wrapHandler(handler))
}

func (r *router) Delete(path string, handler http.Handler) {
r.DELETE(path, wrapHandler(handler))
}

//=======================================================
func NewRouter() *router {
return &router{httprouter.New()}
}

//========================================================
func wrapHandler(h http.Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
context.Set(r, "params", ps)
h.ServeHTTP(w, r)
}
}

func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)

apiC := apiContext{session.DB("test")}

commonHandlers := alice.New(context.ClearHandler, loggingHandler, 
recoverHandler, acceptHandler)
router := NewRouter()

router.Get("/nnrf-nfm/v1/nf-instances", 
commonHandlers.ThenFunc(apiC.GetNfInstanceUrls))
router.Get("/nnrf-nfm/v1/nf-instances/:nfInstanceID", 
commonHandlers.ThenFunc(apiC.GetNfInstancebyID))
router.Patch("/nnrf-nfm/v1/nf-instances/:nfInstanceID", 
commonHandlers.Append(contentTypeHandler, 
bodyHandler(NfInstanceResource{})).ThenFunc(apiC.UpdateNfInstance))
router.Delete("/nnrf-nfm/v1/nf-instances/:nfInstanceID", 
commonHandlers.ThenFunc(apiC.DeregisterNfInstance))
//Retrive a collection of NF instances
router.Get("/nnrf-disc/v1/nf-instances", 
commonHandlers.ThenFunc(apiC.SearchAllNfInstances))
router.Put("/nnrf-nfm/v1/nf-instances/:nfInstanceID", 
commonHandlers.Append(contentTypeHandler, 
bodyHandler(NfInstanceResource{})).ThenFunc(apiC.RegisterNewNfInstance))

//Subscription handlers
router.Post("/nnrf-nfm/v1/subscriptions", 
commonHandlers.Append(contentTypeHandler, 
bodyHandler(NfSubsciptioneResource{})).ThenFunc(apiC.CreateNewSubscription))
router.Patch("/nnrf-nfm/v1/subscriptions/:nfInstanceID", 
commonHandlers.Append(contentTypeHandler, 
bodyHandler(NfSubsciptioneResource{})).ThenFunc(apiC.updateAsubscriptionbyID))
router.Delete("/nnrf-nfm/v1/subscriptions/:nfInstanceID", 
commonHandlers.ThenFunc(apiC.deregisterSubscriptionbyID))

http.ListenAndServe(":8000", router)
}



//Middle ware

type Errors struct {
Errors []*Error `json:"errors"`
}

type Error struct {
Id     string `json:"id"`
Status int    `json:"status"`
Title  string `json:"title"`
Detail string `json:"detail"`
}

var (
ErrBadRequest           = &Error{"bad_request", 400, "Bad request", 
"Request body is not well-formed. It must be JSON."}
ErrNotAcceptable        = &Error{"not_acceptable", 406, "Not Acceptable", 
"Accept header must be set to 'application/json'."}
ErrUnsupportedMediaType = &Error{"unsupported_media_type", 415, 
"Unsupported Media Type", "Content-Type header must be set to: 
'application/json'."}
ErrInternalServer       = &Error{"internal_server_error", 500, "Internal 
Server Error", "Something went wrong."}
)

func acceptHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") != "application/json" {
WriteError(w, ErrNotAcceptable)
return
}

next.ServeHTTP(w, r)
}

return http.HandlerFunc(fn)
}

func contentTypeHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
WriteError(w, ErrUnsupportedMediaType)
return
}

next.ServeHTTP(w, r)
}

return http.HandlerFunc(fn)
}

func recoverHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %+v", err)
WriteError(w, ErrInternalServer)
}
}()

next.ServeHTTP(w, r)
}

return http.HandlerFunc(fn)
}

func loggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
}

return http.HandlerFunc(fn)
}

func bodyHandler(v interface{}) func(http.Handler) http.Handler {
t := reflect.TypeOf(v)

m := func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
val := reflect.New(t).Interface()
err := json.NewDecoder(r.Body).Decode(val)

if err != nil {
WriteError(w, ErrBadRequest)
return
}

if next != nil {
context.Set(r, "body", val)
next.ServeHTTP(w, r)
}
}

return http.HandlerFunc(fn)
}

return m
}

func WriteError(w http.ResponseWriter, err *Error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(err.Status)
json.NewEncoder(w).Encode(Errors{[]*Error{err}})
}


-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to