How to properly handle a PATCH request with Go - http

I have a "Settings" table in my postgresql database with following data :
id | price | duration | start_mn | end_mn | step | days_ranges
----+-------+----------+----------+--------+------+--------------------------------------------------
1 | 50 | 40 | 540 | 1140 | 30 | [{"weekday":3,"ranges":{"from":599, "to":1079}}]
I want to handle a patch request that would edit a single field such as duration for instance.
Atm I have an http request with this body : {duration: 20}
I'd like to know how to properly patch. On my GO backend these structs are set :
type Settings struct {
Price int
Duration int
StartMn int
EndMn int
Step int
DaysRanges DaysRanges
}
type DaysRanges []struct {
WeekDay int
Ranges struct {
From int
To int
}
}
Now the function that handles it for now :
func PatchSettings(w http.ResponseWriter, r *http.Request) {
var settings Settings
err := json.NewDecoder(r.Body).Decode(&settings)
if err != nil {
panic(err)
}
}
So far I got an object Settings with many fields empty (since only the duration is passed in the body). I can then check each field and if it is not empty process an sql update on that specific field with its value.
But I have a feeling it's quite poor understanding of the PATCH request and the way to deal with it.
I'm looking for a better approach.

Related

Why do you have to use an asterisk for pointers but not struct pointers?

I think I am missing a part of technical background. But I don't get, why I have to use an * to access the value of a simple pointer, but not for accessing values of a struct.
For example with a simple value:
func main() {
i := 42
p := &i
*p = 21 // <<< I have to use an asterisk to access the value
// ...
}
And a example with a struct:
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9 // <<< I do not have to use an asterisk
// ...
}
(yes, the samples are from the official go lang tour here: https://go-tour-de.appspot.com/moretypes/4)
Just from my thoughts I would expect something like this
*p.X = 1e9
or (yeah, this would be somewhat strange)
p.*X = 1e9
So, why don't I have to use an asterisk to access struct pointer?
The official Golang tour where you found that example [here] explicitly says:
To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.

How to find out nothing is being received in an unbuffered channel without closing it?

Is there a way to know if all the values in channel has been consumed? I'm making a crawler which recursively fetches sites from seed site. I'm not closing the channel because it consumes from the server and should crawl every time new site is sent. For a given seed site, I can't find a better way to know completion of a subtask other than timing out. If there was a way to know that there is no value in channel(left to be consumed), my program could get out of the sub task and continue listening to the server.
There is no such things as "queued in an unbuffered channel." If the channel is unbuffered, it is by definition always empty. If it is buffered, then it may have some number of elements in it up to its size. But trying to read how many elements are in it is always going to cause race conditions, so don't design that way (it's also impossible in Go).
Ideally, avoid designs that need to know when children are complete, but when you must, send them a channel to respond to you on. When they respond, then you know they're complete.
The kind of problem you're describing is well covered in the Go blogs and talks:
Go Concurrency Patterns: Pipelines and cancellation
Go Concurrency Patterns: Context
Concurrency is not paralellism
Go Concurrency Patterns
Advanced Go Concurrency Patterns
You can determine whether or not a goroutine is blocked on the other end of a channel by using default in a select statement. For example:
package main
import (
"fmt"
"time"
)
var c = make(chan int)
func produce(i int) {
c <- i
}
func consume() {
for {
select {
case i := <-c:
fmt.Println(i)
default:
return
}
}
}
func main() {
for i := 0; i < 10; i++ {
go produce(i)
}
time.Sleep(time.Millisecond)
consume()
}
Keep in mind that this isn't a queue though. If you were to have 1 producing goroutine that looped and produced multiple values between the time it took to send one value and get back around the loop again the default case would happen and your consumer would move on.
You could use a timeout:
case <-time.After(time.Second):
Which would give your producer a second to produce another value, but you're probably better off using a terminal value. Wrap whatever you're sending in a struct:
type message struct {
err error
data theOriginalType
}
And send that thing instead. Then use io.EOF or a custom error var Done = errors.New("DONE") to signal completion.
Since you have a recursive problem why not use a WaitGroup? Each time you start a new task increment the wait group, and each time a task completes, decrement it. Then have an outer task waiting on completion. For example here's a really inefficient way of calculating a fibonacci number:
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func fib(c chan int, n int) {
defer wg.Done()
if n < 2 {
c <- n
} else {
wg.Add(2)
go fib(c, n - 1)
go fib(c, n - 2)
}
}
func main() {
wg.Add(1)
c := make(chan int)
go fib(c, 18)
go func() {
wg.Wait()
close(c)
}()
sum := 0
for i := range c {
sum += i
}
fmt.Println(sum)
}

Printing the words of a trie tree

I was trying to print the contents of a trie in C. However I'm not very sucessful. And also let me say right in the beginning that this something we are doing in school right now, and this is one exercise.
This is how my trie looks like:
struct node{
char letter; //holds the letter associated with that node
int count; //its count
struct node* child[26]; //each node can have 26 children
};
struct trie{
struct node* root;
};
This print method has to traverse this trie and print the words in alphabetic order and the ones that have a count of 0 should not be printed.
I was thinking along recursion and this is what my code looks like:
void print(node* root) {
char buffer[15];//array to store the letters
if(root==NULL){ return;}//if the root is null return
int i;
int index=0; //index for the buffer
int hasAChild=hasChild(root);
if (hasAChild != 0) { //the root has children keep on going
for (i=0;i<27;i++) {
//go thru all the children and if they have children call print recursively
if (hasChild(root->child[i])) {
print(root->child[i]);
}
else {
// if they have no more children add the letter to the buffer
buffer[index++] = root->child[i]->letter;
}
// print the contents in the bufffer
printf("%s: %d",root->child[i]->count);
}
}
}
// function to determine if a node has children, if so it returns their number if not,returns 0
int hasChild(root) {
if(root==NULL){
return 0;
}
int i;
int count=0;
for(i=0;i<27;i++){
if(root->child[i]!=NULL){
count++;
}
}
return count;
}
This is what it would look like
Example of a trie:
Root
+--- a:2
| +--- t:4
|
+--- b:3
| +--- e:5
|
+--- c:0
we have 'a' 2 times, 'at' 4 times, 'b' 3 times and 'be' 5 times, only the words should be printed.
In this example I will have to print
at: 4
be: 5
but not c: 0 since its count is 0
So i'm only suppose to print the words that are formed, not the letters that do not form a word. Any help or guidance would be greatly appreciated. Thank you!
I see three issues here:
you append a letter to the current buffer only when the current node has no children. This means that you will only display the last letter of the words.
in addition, every time you enter the function, you start with an empty buffer.
your printf statement is missing a string argument.
You need to pass the length and the buffer, and make sure to null-terminate it correctly.

Recursively reverse a linkedlist (code in Stanford CSed library) explanation

My recursion skill is pretty rusty. I've been thinking about this problem and searched the forum for a long time but still cannot understand. Right now I'm looking at the recursively reverse a linked list code from Stanford CS ed library.
#include <stdio.h>
struct Node {
int x;
struct Node *next;
};
void Reverse(struct Node ** headRef){
struct Node* first;
struct Node* rest;
if(*headRef==NULL)
return;
first= *headRef;
rest= first->next;
if(rest==NULL)
return;
Reverse(&rest);
printf("Rest%d\n", (rest)->x); // I added this line to print rest
first->next->next=first;
first->next=NULL;
*headRef=rest;
}
void printList(struct Node* head){
if(!head)
return;
else{
printf("%d ", head->x);
printList(head->next);
}
}
void main(){
struct Node *head;
struct Node * node1= (struct Node*) malloc(sizeof(struct Node));
struct Node * node2= (struct Node*) malloc(sizeof(struct Node));
struct Node * node3= (struct Node*) malloc(sizeof(struct Node));
struct Node * node4= (struct Node*) malloc(sizeof(struct Node));
head= node1;
node1->next=node2;
node1->x=1;
node2->x=2;
node3->x=3;
node4->x=4;
node2->next=node3;
node3->next=node4;
node4->next=NULL;
Reverse(&head);
}
Now suppose I have a linked list 1->2->3->4. What I cannot understand is the last line, which will set the headRef to 4 eventually, I think it should set the headRef to 2. I tried to execute the function and it printed out:
4
4
4
for the variable rest.
However, if I commented the last line in the the Reverse function out, it still reversed the list but would print
4
3
2.
The second result I can understand, but the first one seemed quite confusing. Does the statement "*headRef=rest" do any thing to the variable rest? What does it keep pointing to 4?
Also, if I pass *headRef instead of **headRef (last line is not commented out), it would print the result
4
3
2
too.
Could anyone please explain to me what happened in the memory? Thanks a million.
Before the recursive call to Reverse we have:
first---|
|
v
1->2->3->4->NULL
^
|
|
rest------
After the recursive call to Reverse we have:
first---|
|
v
1->2<-3<-4
| ^
v |
NULL |
rest------------
Now we need to fix 2->NULL to 2->1 by first->next->next=first.
first---|
|
v
1<-2<-3<-4
| ^ ^
|--| |
|
rest------------
Now we need to fix 1->2 to 1->NULL by first->next=NULL.
first---|
|
v
NULL<-1<-2<-3<-4
^
|
|
rest------------
Finally *headRef=rest so that *headRef will point to 4 instead of to 1.
What happens here is as because the recursive call passes the address of rest to the local variable headRef, when each recursive call returns, the statement *headRef=rest already changes the address of rest pointer for the statements coming next in the execution flow.
For the linked list 1->2->3->4 :
Let us assume 1 is stored in address 100, 2 in address 200, 3 in address 300 and 4 in address 400.
PART 1:
the call Reverse(&rest) [rest points to address 400]
first = 400
rest = NULL
as rest is NULL the execution returns to the point after Reverse(400) call
PART 2:
Here first = 300 and rest = 400
after execution of first->next->next=first and first->next=NULL
we have *headRef=rest [rest points to 400]
but this headRef was passed an address of rest=300. So now already for the next step in execution,
rest points to 400.
PART 3:
Now execution returns to the point after Reverse(300) call
But during forward call [first was 200 and rest was 300] and during return [rest = 400]. HERE'S THE TRICK!!!
after execution of first->next->next=first and first->next=NULL
we have *headRef=rest [rest points to 400]
but this headRef was passed an address of rest=200. So now already for the next step in execution,
rest points to 400.
PART 4:
Now execution returns to the point after Reverse(200) call
But during forward call [first was 100 and rest was 200] and during return [rest = 400].
after execution of first->next->next=first and first->next=NULL
we have *headRef=rest [rest points to 400]
and as because this is the initial call, the function returns with *headRef having 400 value.
JOB DONE!

How do I use a (generic) vector in go?

I am using a Vector type to store arrays of bytes (variable sizes)
store := vector.New(200);
...
rbuf := make([]byte, size);
...
store.Push(rbuf);
That all works well, but when I try to retrieve the values, the compiler tells me I need to use type assertions. So I add those in, and try
for i := 0; i < store.Len(); i++ {
el := store.At(i).([]byte);
...
But when I run this it bails out with:
interface is nil, not []uint8
throw: interface conversion
Any idea how I can 'cast'/convert from the empty Element interface that Vector uses to store its data to the actual []byte array that I then want to use subsequently?
Update (Go1): The vector package has been removed on 2011-10-18.
This works fine for me. Have you initialised the first 200 elements of your vector? If you didn't they will probably be nil, which would be the source of your error.
package main
import vector "container/vector"
import "fmt"
func main() {
vec := vector.New(0);
buf := make([]byte,10);
vec.Push(buf);
for i := 0; i < vec.Len(); i++ {
el := vec.At(i).([]byte);
fmt.Print(el,"\n");
}
}

Resources