Convert Curl POST into Go code

Folks,
I am currently doing this API POST using curl command in shell script, however I want to create a Go program to make this work instead of shell script curl command. Also would like to take input from stdio for things like management IP, username, password and FirstAddress
here is the command below

 curl -sku admin:admin -H "Content-Type: application/json" -X POST  https://$FIRST_MGMT_IP/mgmt/tm/ltm/pool -d '{"name": "FirstIPFIXPool", "monitor": "gateway_icmp ", "members": [{"name":"'${FirstAddress}':4739", "address":"'$FirstAddress'"}]}' | python -m json.tool

what is the best way to do ?

You can use os.Getenv to retrieve environment variables and os.Args to retrieve arguments given on the command line.

Also there is the net/http package which gives you a full HTTP(S) client which you can use to actually issue the request.

@NobbZ thanks I tried its giving me syntax error at https://play.golang.org/p/AlAXuTwgy51

 package main

import (
 "fmt"
 "os"
 "net/http"
)
func main() {
resp, err := http.PostForm("https://10.192.74.73/mgmt/tm/ltm/pool",
	url.Values{"name":"FirstIPFIXPool", "monitor": "gateway_icmp ", "members":[{"name":"15.1.1.1:4739", "address":"15.1.1.1"}]})
}

You are missing to import net/url to be able to use url.Values.

Then you are using it wrong. url.Values is a map[string][]string.

Also, last but not least, the cURL invocation you have shown in the initial post is not doing a form submission, but its sending a JSON document in its body.

http.Post is probably more what you are searching.

1 Like

Actually, curl will default to POST if -d ‘body’ is provided.

But you’re spot on about needing http.Post instead of http.PostForm.

To get a basic structure you can also translate your curl commands to Go with this nice tool by Matt Holt:

https://mholt.github.io/curl-to-go/

Maybe this helps.

1 Like

My project here emulates curl to some degree: https://github.com/mrichman/hargo

Maybe you can draw inspiration from it.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.