Examples of ResponseValidation By Golang

Check Status Code

package api

import "callapi"
import "net/http"

func (c  CallBack) ResponseValidate(resp *http.Response, ctx *callapi.RestBirdCtx) bool {
	if resp.StatusCode == 200 {
		return true
	}

	return false
}

Check Status Line

package api

import "callapi"
import "net/http"
import "strings"

func (c  CallBack) ResponseValidate(resp *http.Response, ctx *callapi.RestBirdCtx) bool {
	if ret := strings.Contains(resp.Status, "200 OK"); ret {
		return true
	}

	return false
}

Check Response Header

package api

import "callapi"
import "net/http"
import "strings"

func (c  CallBack) ResponseValidate(resp *http.Response, ctx *callapi.RestBirdCtx) bool {
	var  valueofaa string

	// check if header 'aa' is exist or not
	if vv, exist := resp.Header['aa']; !exist {
		return false
	}

	//check if heaer 'aa' 's value contains 'hello world'
	for k, vv := range resp.Header {
		for _, v := range vv {
			if k == "aa" {
				if ret := strings.Contains(v, "hello world"); ret {
					return true
				}
			}
		}
	}


	return false
}

Check Response Text Body

package api
import "callapi"
import "net/http"
import "io/ioutil"
import "strings"
import "fmt"

func (c  CallBack) ResponseValidate(resp *http.Response, ctx *callapi.RestBirdCtx) bool {
	var data string
	var body []byte
	var err error

	if body, err = ioutil.ReadAll(resp.Body); err != nil {
		fmt.Println("read body failed.")
		return true
	}

	data = string(body)
	if ret := strings.Contains(data, "hello world"); ret {
		return true
	}

	fmt.Println(data)

	return false
}

Check Response Json Body

package api
import "callapi"
import "net/http"
import "io/ioutil"
import	"encoding/json"
import "fmt"

type MyDATA struct {
	Aa    string `json:"aa, omitempty"`
	Bb    int `json:"bb, omitempty"`
	Cc    bool `json:"cc, omitempty"`
}

func (c  CallBack) ResponseValidate(resp *http.Response, ctx *callapi.RestBirdCtx) bool {
	var body []byte
	var err error
	var data MyDATA

	if body, err = ioutil.ReadAll(resp.Body); err != nil {
		fmt.Println("read body failed.")
		return true
	}

	if err = json.Unmarshal(body, &data); err != nil {
		fmt.Println("conver body to json failed:", err.Error())
		return true
	}

	if data.Aa == "hello world" {
		return true
	}

	return false
}

Access Varibles

package api

import "callapi"
import "net/http"
import "fmt"
import "time"

func (c  CallBack) ResponseValidate(resp *http.Response, ctx *callapi.RestBirdCtx) bool {

	hellovars := ctx.GetVars("hello")
	fmt.Println("hello var is: " + hellovars)

	ctx.SetVars("hello", "I am not world")

	var mytime  time.Time
	if err := callapi.GetGlobalVars("currTime", &mytime); err != nil {
		return  true
	}

	mytime =  time.Now()
	if err := callapi.SetGlobalVars("currTime", mytime); err != nil {
		return true
	}

	if err, mytoken := callapi.GetGlobalString("mytoken"); err != nil {
		return true
	 } else {
		callapi.SetGlobalString("mytoken", "hello world token")
	}

	return true
}